<%@ page import="com.pijunn.label.*" %>
<!DOCTYPE html>
<html>
	<head>
		<meta name="layout" content="main">
		<g:set var="entityName" value="${message(code: 'labeledItem.label', default: 'Labeled Items')}" />
		<title><g:message code="default.create.label" args="[entityName]" /></title>
		<style type="text/css" media="screen">
			textarea {
				height: 100px;
				margin: 0 15px 0 0;
			}
			input {
				margin-right: 15px;
			}
			.item-div {
				margin: 5px 0;
			}
			.label-display {
				display: inline-block;
				margin-right: 15px;
			}
			.fieldcontain {
				display: inline-block;
			}
			.no-labels p {
				font-size: 1.4em;
				color: darkseagreen;
				padding: 10px 50px;
			}
			.no-labels input {
				display:inline;
			}
		</style>
	</head>
	<body>
		<a href="#create-labeledItem" class="skip" tabindex="-1"><g:message code="default.link.skip.label" default="Skip to content&hellip;"/></a>
		<div class="nav" role="navigation">
			<ul>
				<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
				<li><g:link class="list" action="list"><g:message code="default.list.label" args="[entityName]" /></g:link></li>
			</ul>
		</div>
		<div id="create-labeledItem" class="content scaffold-create" role="main">
			<h1><g:message code="default.create.label" args="[entityName]" /></h1>
			<g:if test="${flash.message}">
			<div class="message" role="status">${flash.message}</div>
			</g:if>
			<g:hasErrors bean="${cmd}">
			<ul class="errors" role="alert">
				<g:eachError bean="${cmd}" var="error">
				<li <g:if test="${error in org.springframework.validation.FieldError}">data-field-id="${error.field}"</g:if>><g:message error="${error}"/></li>
				</g:eachError>
			</ul>
			</g:hasErrors>
			<g:form action="save" >
				<g:if test="${!labelList}">
					<div class="no-labels">
						<p>Do you have your labels yet?  If not, would you like to <a href="http://www.pijunn.com/Shop">purchase high quality tags</a> from us, or <g:link action="generate">print</g:link> your own?</p>
						<p>If you have already purchased labels, check back when they arrive to register your labeled items with us.</p>
						<p>If you have your labels, click <a id="registerRange" href="#">here</a><span style="display: none;">, or enter the count of the items would you like to register: <input id="generate-count" type="text" maxlength="2" size="2"/></span></p>
					</div>
				</g:if>
				<fieldset class="form">
					<g:each in="${labelList}" var="label" status="i">
						<g:render template='labeledItem' model="['item':label,'i':i,'hidden':false, 'cmd':cmd]"/>
					</g:each>
					<span style="display: none;"><button id="addLabel" tabindex="99">Add another Label</button></span>
				</fieldset>
				<fieldset class="buttons">
					<g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
				</fieldset>
			</g:form>
			<g:render template='labeledItem' model="['item':templateLabel,'i':'-template','hidden':true, 'cmd':cmd]"/>
		</div>
		
		<div id="dialog-form" title="Claim Labels">
		    <p class="validateTips">All form fields are required.</p>
		 
		    <g:form action="assign">
		    <fieldset>
		        <label for="startSerialNumber">Start Serial:</label>
				<span class="required-indicator">*</span>
			    <g:textField name="startSerialNumber"  hint="Low Serial #"/>
		        <label for="endSerialNumber">End Serial:</label>
				<span class="required-indicator">*</span>
			    <g:textField name="endSerialNumber"  hint="High Serial #"/>
			    <g:hiddenField name="user.id" value="${user.id}"/>
		    </fieldset>
		    <p class="message">If you have a strip of labels, enter the lowest and highest serial numbers.  If you have a single label of a key fob, enter the number twice.</p>
		    </g:form>
		</div>
	</body>
	<g:javascript>
	$(function(){
		
		$('#addLabel')
			.button()
			.click(function(){
				addRow();
				return false;			
			});
	
		 $('.item-div').on('click', '.del-item', function(){
			clearRow($(this).parentsUntil('.form').last());
		}); 
		
		$('#generate-count').on('blur', function(){
			var iter = $(this).val();
			for (var i=0; i < iter; i++) {
				addRow();
			}
			
			$('.no-labels').hide()
		});
		
		function addRow() {
				// Add a new row
				var offset = $('.item-div').length - 1;
				var newRow = $('#item-template').clone().attr('id', 'item'+offset);
				$('#serial-template', newRow).attr('id', 'serial'+offset);
				newRow.show().insertBefore('#addLabel');
				newRow.on('click', '.del-item', function(){
					clearRow($(this).parentsUntil('.form').last());
				}); 
				$('#description', newRow).val($('#description', newRow).attr('hint'))
		}
		
		function clearRow(row) {
			$('#name', row).val($('#name', row).attr('hint')).blur();
			$('#description', row).val($('#description', row).attr('hint')).blur();
			if ($('#regLabel', row).val() == 'false') {
				row.remove();
			}
		}
		
		var start = $( "#startSerialNumber" ),
            end = $( "#endSerialNumber" ),
            allFields = $( [] ).add( start ).add( end ),
            tips = $( ".validateTips" );
            
	            
	function updateTips( t ) {
	    tips
	        .text( t )
	        .addClass( "ui-state-highlight" );
	    setTimeout(function() {
	        tips.removeClass( "ui-state-highlight", 1500 );
	    }, 500 );
	}
	
	function checkLength( o, n, min, max ) {
	    if ( o.val().length > max || o.val().length < min ) {
	        o.addClass( "ui-state-error" );
	        updateTips( "Length of " + n + " must be between " +
	            min + " and " + max + "." );
	        return false;
	    } else {
	        return true;
	    }
	}
	
	function checkRegexp( o, regexp, n ) {
	    if ( !( regexp.test( o.val() ) ) ) {
	        o.addClass( "ui-state-error" );
	        updateTips( n );
	        return false;
	    } else {
	        return true;
	    }
	}
	
	function compare(o, p, r, n) {
		var min = parseInt(o.val()), max = parseInt(p.val());
		if (typeof(min) == 'number' && typeof(max) == 'number') {
			var check = p.val() - o.val(), val = 0;
			if(check >= 0) val = 1;
			else if (check < 0) val = -1;	
			
			if (val != r) {
		        o.addClass( "ui-state-error" );
		        updateTips( n );
		        return false;
		    } else {
		        return true;
		    }
		}
	}
            
   	$( "#dialog-form" ).hide()
		.dialog({
            autoOpen: false,
            height: 360,
            width: 350,
            modal: true,
            buttons: {
                "Claim Labels": function() {
                    var bValid = true;
                    allFields.removeClass( "ui-state-error" );
 
                    bValid = bValid && checkLength( start, "start Serial #", 8, 8 );
                    bValid = bValid && checkLength( end, "end Serial", 8, 8 );
  
                    bValid = bValid && checkRegexp( start, /^[0-9]+$/i, "Start Serial must be numeric." );
                    bValid = bValid && checkRegexp( end, /^[0-9]+$/i, "End Serial must be numeric." );
                    
                    bValid = bValid && compare(start, end, 1, "Start Serial must be less than or equal to End Serial");
 
                    if ( bValid ) {
                    var qty = parseInt(end.val()) - parseInt(start.val()) + 1;
                        $( ".message" ).append( "<b>You are claiming" +
                            qty + " labels</b>");
                        if (qty > 10) {
                        	if (confirm("You are claiming " + qty + " labels, which is kind of a lot. Are you sure about this?")) {
                        		$( '#dialog-form form' ).submit();
                        	}
                        	else
                        		return;
                        }
                        else {
                        	$( '#dialog-form form' ).submit();
                        }
                        $( this ).dialog( "close" );
                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });
 
        $( "#registerRange" )
            .button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
        });
	});
	</g:javascript>
</html>
